<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { formatNumber } from '@/home/utils/format';
import {
  Chart,
  LineController,
  LineElement,
  PointElement,
  CategoryScale,
  LinearScale,
  Tooltip,
  Filler,
  type ScriptableContext,
  type ChartConfiguration,
  type TooltipItem,
} from 'chart.js';
import { useFetch } from '@/home/hooks/fetch';
import { format, parse } from 'date-fns';
import { useI18n } from 'vue-i18n';

Chart.register(
  LineController,
  LineElement,
  PointElement,
  CategoryScale,
  LinearScale,
  Tooltip,
  Filler,
);

const { t } = useI18n();
const { $fetch } = useFetch();
const chartEl = ref();
const detail = ref<Record<string, any>>({});
const currentKey = ref('userCountMap');
const titleMap = ref<Record<string, string>>({
  userCountMap: t('home.home.communityData.people.total'),
  warehouseCountMap: t('home.home.communityData.repository.total'),
  orgCountMap: t('home.home.communityData.organization.total'),
});

const createRadialGradient3 = (context: ScriptableContext<'line'>, color: string) => {
  const ctx = context.chart.ctx;
  const gradient = ctx.createLinearGradient(0, 220, 0, 0);
  gradient.addColorStop(0, color + '00'); // 渐变起始颜色，透明度0%
  gradient.addColorStop(1, color + '59'); // 渐变结束颜色，透明度60%

  return gradient;
}

let chartInstance: Chart<'line', number[], number>;
const option: ChartConfiguration<'line', number[], number> = {
  type: 'line',
  options: {
    elements: {
      line: {
        tension: 0.4,
      },
    },
    interaction: {
      intersect: false,
      mode: 'index',
    },
    scales: {
      x: {
        display: true,
        border: {
          color: '#52CEBC',
          dash: [4, 2],
          width: 2,
        },
        ticks: {
          backdropColor: '#52CEBC',
          color: '#52CEBC',
          textStrokeWidth: 12,
          major: {
            enabled: true,
          },
          callback(value) {
            return format(parse(this.getLabelForValue(value as number), 'yyyy-MM-dd', new Date()), 'd');
          },
        },
      },
      y: {
        display: false,
      },
    },
    plugins: {
      tooltip: {
        callbacks: {
          title(context: TooltipItem<'line'>[]) {
            return format(parse(context[0].label, 'yyyy-MM-dd', new Date()), 'yyyy-MM-dd');
          },
        },
      },
    },
  },
  data: {
    labels: [],
    datasets: [
      {
        data: [],
        borderWidth: 3,
        borderColor: '#3D7CFA',
        backgroundColor(context: ScriptableContext<'line'>) {
          return createRadialGradient3(context, '#3D7CFA');
        },
        pointStyle: 'circle',
        pointRadius: 2,
        pointHoverRadius: 3,
        fill: true,
      },
    ],
  },
};

const refresh = async () => {
  const { isSuccess, data } = await $fetch('/record/home');

  if (isSuccess) {
    detail.value = data;

    setData(currentKey.value);
  }
}

const setData = (key: string) => {
  currentKey.value = key;

  const labels: number[] = [];
  const values: number[] = [];

  chartInstance.data.labels = [];
  chartInstance.data.datasets[0].data = [];
  chartInstance.update();

  Array.from((detail.value[currentKey.value]) as any[]).reverse().forEach((item: Record<string, any>) => {
    labels.push(item.x);
    values.push(item.y);
  });

  chartInstance.data.labels = labels;
  chartInstance.data.datasets[0].label = titleMap.value[key];
  chartInstance.data.datasets[0].data = values;
  chartInstance.update();
}

onMounted(async () => {
  await nextTick();

  refresh();

  chartInstance = new Chart(chartEl.value as HTMLCanvasElement, option);
});

onUnmounted(() => {
  chartInstance.destroy();
});
</script>

<template>
  <section class="mt-20 rounded-4 bg-hex-fff p-20 pt-16 shadow-[0_1px_6px_0_rgba(0,0,0,0.04)]">
    <p>{{ titleMap[currentKey] }}</p>
    <canvas ref="chartEl"></canvas>
    <div class="mt-15 flex justify-between px-20px">
      <div class="cursor-pointer" @click="setData('userCountMap')">
        <div class="text-center text-20 color-hex-292929 font-600">{{ formatNumber(detail.userCounts) }}</div>
        <div class="text-center text-12 text-hex-8B8B8B leading-22">{{ $t('home.home.communityData.people.title') }}</div>
      </div>
      <div class="cursor-pointer" @click="setData('warehouseCountMap')">
        <div class="text-center text-20 color-hex-292929 font-600">{{ formatNumber(detail.warehouseCounts) }}</div>
        <div class="text-center text-12 text-hex-8B8B8B leading-22">{{ $t('home.home.communityData.repository.title') }}</div>
      </div>
      <div class="cursor-pointer" @click="setData('orgCountMap')">
        <div class="text-center text-20 color-hex-292929 font-600">{{ formatNumber(detail.orgCounts) }}</div>
        <div class="text-center text-12 text-hex-8B8B8B leading-22">{{ $t('home.home.communityData.organization.title') }}</div>
      </div>
    </div>
  </section>
</template>

<style lang="scss" scoped>
</style>
